package client.shoppingCartFrame;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.List;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.*;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

// This class is a special version of a scrollable list that
// associates an object with each element in the list.

@SuppressWarnings("serial")
public class ObjectList extends JPanel implements TableModelListener
{
	private List list;
	private Vector<Object> objects;	// the objects that correspond to list entries
	private JScrollPane listScrollPane; 
	
	// Table shoppingCart
	private JTable table;
	private Vector rows;
	private Vector columns;
	private DefaultTableModel tabModel;
	private JScrollPane tableScrollPane;
	
	//Table itemPicker
	private JTable itemType;
	private Vector itemPickerRows;
	private Vector itemPickerColumns;
	private DefaultTableModel itemPickerTabModel;
	private JScrollPane itemPickerScrollPane;
	private JToggleButton a;
	private ButtonGroup grp= new ButtonGroup();;
	private ArrayList <JToggleButton> listofButtons = new ArrayList<JToggleButton>();
	

	public ObjectList()
	{
		list = new List();
		objects = new Vector<Object>();
		
		list.setPreferredSize(new Dimension (300, 200));
	}

	public ObjectList(int items, boolean multiSelect)
	{
		list = new List (items, multiSelect);
		//super(items, multiSelect);
		objects = new Vector<Object>();
		
	}
	
	public void initTableShoppingCart()
	{
		rows = new Vector();
		columns= new Vector();
		String[] columnNames = { "Type", "Quantity","Price"};
		addColumns(columnNames);
		
		tabModel=new DefaultTableModel();
		tabModel.fireTableDataChanged();
		tabModel.setDataVector(rows,columns);
		


		table = new JTable(tabModel){
			public boolean isCellEditable(int rowIndex, int collIndex)
		{
				return false;
		}
		};
		tableScrollPane= new JScrollPane(table);//ScrollPane
		
		Font font = new Font("Arial", Font.TRUETYPE_FONT, 14);
		table.getTableHeader().setFont(font);
		table.getTableHeader().setPreferredSize(new Dimension(10,30));
		table.setFont(font);
		table.setRowSelectionAllowed(true);
		table.setRowHeight(25);
		table.setShowGrid(false);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		  table.getColumnModel().getColumn(0).setPreferredWidth(180);
		  table.getColumnModel().getColumn(1).setPreferredWidth(70);
		  table.getColumnModel().getColumn(2).setPreferredWidth(110);
          //setColumnWidth(table.getColumnModel().getColumn(1), 100);
		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		
		
		DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
		rightRenderer.setHorizontalAlignment(JLabel.RIGHT);
		table.getColumnModel().getColumn(2).setCellRenderer(rightRenderer);
		
		DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
		centerRenderer.setHorizontalAlignment(JLabel.CENTER);
		table.getColumnModel().getColumn(1).setCellRenderer(centerRenderer);


		table.getModel().addTableModelListener(this);
		
		//add(list);
		tableScrollPane.getViewport().setBackground(Color.WHITE);
		tableScrollPane.setBorder(BorderFactory.createEmptyBorder());
		add(tableScrollPane);
		
	}


	public void initTableItemPicker()
	{
		
		
		itemPickerRows = new Vector();
		itemPickerColumns= new Vector();
		String[] columnName = {"Type", "Price per unit"};
		itemPickerAddColumns(columnName);
		
		itemPickerTabModel=new DefaultTableModel();
		itemPickerTabModel.fireTableDataChanged();
		itemPickerTabModel.setDataVector(itemPickerRows,itemPickerColumns);

		itemType = new JTable(itemPickerTabModel){
			public boolean isCellEditable(int rowIndex, int collIndex)
		{
				return false;
		}
		};
		
		itemType.setRowHeight(25);
		itemPickerScrollPane= new JScrollPane(itemType);//ScrollPane

		TableCellRenderer renderer = new CellRenderer();
		try {
			itemType.setDefaultRenderer( Class.forName( "java.lang.Object" ), renderer );
		}
		catch( ClassNotFoundException ex ) {
			JOptionPane.showMessageDialog( this, "Error rendering table" );
		}

		itemType.setShowGrid(false);
		itemType.setShowHorizontalLines(true);
		itemType.setRowSelectionAllowed(true);
		
		DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
		rightRenderer.setHorizontalAlignment(JLabel.RIGHT);
		itemType.getColumnModel().getColumn(1).setCellRenderer(rightRenderer);
		
		Dimension dim = new Dimension (60,0);
		itemType.setIntercellSpacing(new Dimension(dim));
		
		itemType.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);


		itemType.getModel().addTableModelListener(this);
		
		//add(list);
		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout());
		/*for (int i = 0; i < listofButtons.size(); i++){
			add(listofButtons.get(i));
		}*/
	/*	while (litr.hasNext()){
			panel.add(litr.next());
		}*/
		
		
		//add(listScrollPane);

		//add(listofButtons.get(0));
		//add(new JToggleButton("B"));
		//add(new JToggleButton("C"));
		
	}
	
	public JPanel addJPanel(){
		for (int i = 0; i < listofButtons.size(); i++){
		add(listofButtons.get(i));
	}
		
		return this;
	}
	
	public synchronized void addObject(Object ob)
	{
		rows.add((Vector)ob);
// add a string version of the object to the list
		list.add(ob.toString());

// add the object itself to the object vector
		objects.addElement(ob);
	}


	public synchronized void addObject(Object ob, int position)
	{
		rows.add(position, (Vector) ob);
// add a string version of the object to the list
		list.add(ob.toString(), position);

// add the object itself to the object vector
		if (position >= objects.size()) {
			objects.addElement(ob);
		} else {
			objects.insertElementAt(ob.toString(),
				position);
		}
	}

	public synchronized void addObject(String label, Object ob)
	{
// Allow the object to be assigned a label independently of the object
		list.add(label);
		objects.addElement(ob);
	}
	
	// Altered version of the addObject method to be used to buid the ItemPicker
	// table.
	public synchronized void addObject(String label, BigDecimal number, Object ob)
	{
		JToggleButton button = new JToggleButton ("<html><center>"+ label +"<br>" + number.toString());
		//button.setHorizontalAlignment(SwingConstants.CENTER);
		//button.setToolTipText(number.toString());
		listofButtons.add(button);
		grp.add(button);
		Vector t = new Vector();
		t.addElement(label);
		t.addElement(number + " Kr");
		
		itemPickerRows.add(t);
		
		
		list.add(label);
		objects.addElement(ob);
	}


	// Altered version of the method above to allow to build the 
	// table that supports ShoppingCart.
	public synchronized void addObject(Vector v, String label, Object ob)
	{
		rows.add(v);
		list.add(label);
		objects.addElement(ob);
		table.addNotify();
	}
	
	public synchronized void addObject(String label, Object ob,
		int position)
	{
// Allow the object to be assigned a label independently of the object
		list.add(label, position);
		if (position >= objects.size()) {
			objects.addElement(ob);
		} else {
			objects.insertElementAt(ob.toString(),
				position);
		}
	}
	
	// Altered verion of the method above to allow JTable
	public synchronized void addObject(Vector v, String label, Object ob,
			int position)
	{
		rows.add(position, v);
		table.addNotify();
		
		// Allow the object to be assigned a label independently of the object
				list.add(label, position);
				if (position >= objects.size()) {
					objects.addElement(ob);
				} else {
					objects.insertElementAt(ob.toString(),
						position);
				}
	}


	public synchronized void delObject(Object ob)
	{
// See if the object is in the vector
		int index = objects.indexOf(ob);

// If not, just return
		if (index < 0) return;

// Remove the object from the vector
		objects.removeElementAt(index);

// Remove the list entry
		list.remove(index);
		
		rows.remove(index);
		table.addNotify();
	}

	public synchronized Object getSelectedObject()
	{
// Get the index of the current selection
		int i = -1;
		for (int a = 0; a < listofButtons.size(); a ++)
		{
			if (listofButtons.get(a).isSelected())
				i = a;
				
		}
		
		//int i = list.getSelectedIndex();
		//int i = itemType.getSelectedRow();

		if (i == -1) return null;

// Return the object currently selected
		return objects.elementAt(i);
	}
	
	public synchronized Object getSelectedObjectShoppingCart()
	{
// Get the index of the current selection
	
		//int i = list.getSelectedIndex();
		int i = table.getSelectedRow();

		if (i == -1) return null;

// Return the object currently selected
		return objects.elementAt(i);
	}

	public synchronized Object[] getSelectedObjects()
	{
// Get the indices of all the selected objects
		int[] selectedItems = list.getSelectedIndexes();

// Create an array of all the selected objects
		Object[] whichObjects = new Object[
			selectedItems.length];

		for (int i=0; i < selectedItems.length; i++) {
			whichObjects[i] = objects.elementAt(i);
		}

		return whichObjects;
	}

	public int indexOf(Object ob)
	{
// Locate a particular object
		return objects.indexOf(ob);
	}

	public Object objectAt(int index)
	{
// Return the object at a particular index
		return objects.elementAt(index);
	}

	public void replaceObject(Object ob, int index)
	{
// Change a specific entry in the vector
		list.replaceItem(ob.toString(), index);

// Change a specific entry in the list
		objects.setElementAt(ob, index);
	}

	public void replaceObject(String label, Object ob, int index)
	{
// Change a specific entry in the vector
		list.replaceItem(label, index);

// Change a specific entry in the list
		objects.setElementAt(ob, index);
	}
	
	public void replaceObject (Vector v, String label, Object ob, int index)
	{
		rows.setElementAt(v, index);
		table.addNotify();
		table.repaint();
		
		// Change a specific entry in the vector
				list.replaceItem(label, index);

		// Change a specific entry in the list
				objects.setElementAt(ob, index);
	}
	
	public void deleteAllObjects()
	{
		// Get the indices of all the selected objects
				int[] selectedItems = 	list.getSelectedIndexes();
				//int[] selectedTableItems = rows.getSegetSelectedRows();

		// Create an array of all the selected objects
				/*Object[] whichObjects = new Object[
					selectedItems.length];*/

				for (int i=0; i < selectedItems.length; i++) {
					delObject(objects.elementAt(i));
				}
				
	}
	
	public void addColumns(String[] colName)//Table Columns
	{
		for(int i=0;i<colName.length;i++)
			columns.addElement((String) colName[i]);
	}
	
	public void itemPickerAddColumns(String[] colName)//Table Columns
	{
		for(int i=0;i<colName.length;i++)
			itemPickerColumns.addElement((String) colName[i]);
	}
	
	public void tableChanged(javax.swing.event.TableModelEvent source)     {
		String msg="";
		TableModel tabMod = (TableModel)source.getSource();
		switch (source.getType())
		{
		case TableModelEvent.UPDATE:
			/*msg="Table Value Updated for  cell "+table.getSelectedRow()+","+table.getSelectedColumn()+"\nWhich is "+table.getValueAt(table.getSelectedRow(),table.getSelectedColumn()).toString();
			JOptionPane.showMessageDialog(null,msg,"Table Example",JOptionPane.INFORMATION_MESSAGE);*/
			break;

		}

	}//Table Changed Method
	
	class CellRenderer extends DefaultTableCellRenderer {
		private JTextField field;
		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
			Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			Font font = new Font("Arial", Font.TRUETYPE_FONT, 14);

	   		JTableHeader h = table != null ? table.getTableHeader() : null;
	   		
	   		

		   	if( isSelected ) {
				setBackground( Color.WHITE );
				setForeground( Color.black );
			}
			else {
				if( String.valueOf(value).equals("?") ) {
					cell.setBackground( new Color(29,245,0) );
					cell.setForeground(Color.white);
				}
				else {
					cell.setBackground( Color.white );
					cell.setForeground(Color.black);
				}
		   	}
			if( hasFocus )
				setForeground( new Color(242,185,185) );
			
			/*if (row % 2 == 0){
	   			cell.setBackground(Color.cyan);
	   		}*/
			

		   	cell.setFont(font);
			return this;

		}
		public CellRenderer() {
	        setHorizontalAlignment(SwingConstants.LEFT);
	    }
	}

}

